import 'dart:io';

void main() async {
  final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
  print('Listening for connections on ${server.address.address}:${server.port}');

  await for (HttpRequest request in server) {
    String clientIp;

    // 尝试从 X-Forwarded-For 头部获取客户端 IP
    String? xForwardedFor = request.headers.value('X-Forwarded-For');
    if (xForwardedFor != null && xForwardedFor.isNotEmpty) {
      clientIp = xForwardedFor.split(',')[0].trim();
    } else {
      // 如果没有 X-Forwarded-For，使用远程地址
      clientIp = request.connectionInfo?.remoteAddress.address ?? 'Unknown';
    }

    request.response
      ..headers.contentType = ContentType.text
      ..write('Your IP address is: $clientIp')
      ..close();
  }
}